package top.zigaoliang.javaapi;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @ClassName TestCreateSession
 * @Author hanlin
 * @Date 2019/8/16 15:39
 *
 * 通过两种方式获取连接，后面一种更为安全，尽量使用后面的方法获取
 **/
public class TestCreateSession {

    public static final String SERVER = "192.168.100.21:2181";
    public static final int SERVER_TIMEOUT = 30000;

    private CountDownLatch cdl = new CountDownLatch(1);

    @Test
    /**
     * @Author hanlin
     * @Date 2019/8/16 15:43
     * @Description 以前的方式获取连接,存在问题连接并没有完全创建成功就开始操作，可能会有问题
     * @param
     * @return void
     **/
    public void getSession1() throws Exception{
        ZooKeeper zk = new ZooKeeper(SERVER,SERVER_TIMEOUT,null);
        System.out.println(zk.getState()); //CONNECTING  表示正在连接中
        zk.exists("/test",null);
        System.out.println(zk.getState()); //CONNECTED
    }

    @Test
    /** 确保获取连接成功以后 再进行后续的操作 */
    public void getSession2() throws IOException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(SERVER, SERVER_TIMEOUT, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
                    System.out.println("获取连接成功！");
                    cdl.countDown();
                }
            }
        });
        cdl.await();//等待获取连接成功
        System.out.println(zk.getState());//通过CountDownLatch确保状态为连接成功 CONNECTED
    }
}
